package crontab

import (
	"github.com/robfig/cron/v3"
	"github.com/vueadmin/global"
	"github.com/vueadmin/utils"
	"github.com/vueadmin/utils/conv"
	"time"
)

var cronMap = make(map[uint]*cron.Cron)

func newWithSeconds() *cron.Cron {
	nyc, _ := time.LoadLocation("Asia/Shanghai")
	secondParser := cron.NewParser(cron.Second | cron.Minute |
		cron.Hour | cron.Dom | cron.Month | cron.DowOptional | cron.Descriptor)
	return cron.New(cron.WithParser(secondParser), cron.WithChain(), cron.WithLocation(nyc))
}

// 启动
func Start(target string, cronType int, rule string, id uint) {
	c := newWithSeconds()
	c.AddFunc(rule, func() {
		if cronType == 1 {
			utils.NewHttpRequest().Request("GET", target, nil)
		} else {
			ExecuteMethod(GetTask(target))
		}
		global.DB.Model(&Crontab{}).Where("crontab_id", id).Update("last_run_time", conv.NowUnix())
	})
	cronMap[id] = c
	c.Start()
}

// 执行方法
func ExecuteMethod(fn func()) {
	fn()
}

// 停止任务
func Stop(taskId uint) {
	cronMap[taskId].Stop()
	delete(cronMap, taskId)
}
